﻿// 比拚動畫
$(function () {
    $("#gotop").click(function () {
        jQuery("html,body").animate({
            scrollTop: 0
        }, 1000);
    });
    $(window).scroll(function () {
        if ($(this).scrollTop() > 300) {
            $('#gotop').fadeIn("fast");

        } else {
            $('#gotop').stop().fadeOut("fast");
        }
    });
});

$(function () {
    var w = $(".compare-box-container").height();
    $('.compare-box-container').css('top', '-' + w + 'px');  //將比拼區塊 登入後不要直接出現
    var state = true;

    $("#toolBarPlus").click(function () { //按鈕按下去時
        if ($(".compare-box-container").css('top') == '-' + w + 'px' && state) {
            $(".compare-box-container").animate({ top: '50px' }, 800, 'easeOutQuint');
        }
        else {
            //再按一次後
            $(".compare-box-container").animate({ top: '-' + w + 'px' }, 800, 'easeOutQuint');
        }
        state = !state
    });
});

// ubox items 的 btn
function itemMouseEnter() {
    $(this).find('button').show();
    $(this).find('img').css('opacity', '0.9');
};

function itemMouseLeave() {
    $(this).find('button').hide();
    $(this).find('img').css('opacity', '1');
};

// ubox item add to compare box
function addBtnCompare() {
    $('#main-container, .ubox-content').on('click', '.btn-compare', function () {
        var productId = $(this).children('span').attr('class');
        addItemToCompareBox(productId);
    });
}

$('.compare-item-phone, .compare-item-pad, .compare-item-wear').hide();

// function add to compare box
function addItemToCompareBox(productId) {
    
    productId = parseInt(productId);
    $.get("Handler/HandlerCompare.ashx",
         { status: 'addItemToCompareBox', productId: productId },
         function (data) {
             var Image = 'images/defaultPhone.png';
             var Name = data.Name.substr(0, 30);
             var ID = data.ID;
             var CategoryID = data.CategoryID;
             if (data.Image != null) {
                 Image = "data:image/jpg;base64," + data.Image;
             }
             var CompareType;
            
             switch (CategoryID) {
                 case 1: 
                     CompareType = ".compare-item-phone";
                     showCpBoxPhone();
                     break;
                 case 2:
                     CompareType = ".compare-item-pad";
                     showCpBoxPad();
                     break;
                 case 3:
                     CompareType = ".compare-item-wear";
                     showCpBoxWear();
                     break;
             };
             
             switch (addCompareItemToCookie(ID, CategoryID)) {

                    case 'add':
                            var item = '<div class="compare-box-item">' +
                                                            '<div class="compare-img-container">' +
                                                            '<img class="box-item-img" src="' + Image + '" />' +
                                                            '</div>' +
                                                            '<p>' + Name + '</p>' +
                                                            '<div class="compare-box-cancel">' +
                                                            '<div class="'+ID+'">'+
                                                            '<img class="' + CategoryID + '" src="images/icon-cancel-130.png" />' +
                                                            '</div>' +
                                                            '</div>' +
                                                            '</div>';
                            $(CompareType).append(item);
                            uboxWarning('加入比拚');
                            
                            $(".compare-box-item").fadeTo(500, 1);   

                            break;
                 case 'alreadyAdd':
                     uboxWarning('此UBOX商品已加入比拚');
                     break;
                 case 'moreThanFive':
                     uboxWarning('已超過五樣商品');
                     break;
             }
             $(".compare-box-container").animate({ top: '50px' }, 1500, 'easeOutQuint');   //跳出比拼框
             //$(".compare-box-item").animate({ opacity: 1 }, 4000, 'easeOutCubic');   //跳出比拼框
         }); 
    
}

// function add select item to cookie
function addCompareItemToCookie(ID, CategoryID) {
    var cookieType;
    switch (CategoryID) {
        case 1:
            cookieType = 'phone';
            break;
        case 2:
            cookieType = 'pad';
            break;
        case 3:
            cookieType = 'wear';
            break;
    }
    var arr = [];
    if ($.cookie(cookieType) == null) {
        arr.push(ID);
        $.cookie(cookieType, arr);
        return 'add';
    }
    else {
        arr = $.cookie(cookieType).split(',');
        if ($.inArray(ID + '', arr) == -1) {
            if (arr.length < 5) {
                arr.push(ID);
                arr.sort(function (a, b) { return a - b; });
                $.cookie(cookieType, arr);
                return 'add';
            }
            else {
                return 'moreThanFive';
            }
        }
        else {
            return 'alreadyAdd';
        }
    }
}

// compare box selected tip
$('.compare-box-phone, .compare-box-pad, .compare-box-wear').click(function () {
    switch ($(this).attr('class').split(' ')[0]) {
        case 'compare-box-phone':
            showCpBoxPhone();
            break;
        case 'compare-box-pad':
            showCpBoxPad();
            break;
        case 'compare-box-wear':
            showCpBoxWear();
            break;
    }
})

function showCpBoxPhone() {
    $('.compare-item-pad, .compare-item-wear').hide();
    $('.compare-item-phone').show();
    $('.compare-box-pad, .compare-box-wear').removeClass('compare-cate-choose');
    $('.compare-box-phone').addClass('compare-cate-choose');
}

function showCpBoxPad() {
    $(' .compare-item-phone, .compare-item-wear').hide();
    $('.compare-item-pad').show();
    $(' .compare-box-phone, .compare-box-wear').removeClass('compare-cate-choose');
    $('.compare-box-pad').addClass('compare-cate-choose');
}

function showCpBoxWear() {
    $(' .compare-item-phone, .compare-item-pad').hide();
    $('.compare-item-wear').show();
    $('.compare-box-phone, .compare-box-pad').removeClass('compare-cate-choose');
    $('.compare-box-wear').addClass('compare-cate-choose');
}

// delete compare box items
$('.compare-box-middle').on('click', '.compare-box-cancel', function () { deleteCompareBoxItem($(this)) });

function deleteCompareBoxItem(elem) {
    var $this = elem;
    var ID = $this.children('div').attr('class');
    var CategoryID = parseInt($this.find('img').attr('class'));
    $this.parent('.compare-box-item').remove();
    var cookieType;
    switch (CategoryID) {
        case 1:
            cookieType = 'phone';
            break;
        case 2:
            cookieType = 'pad';
            break;
        case 3:
            cookieType = 'wear';
            break;
    }
    var arr = [];
    if ($.cookie(cookieType) != null) {
        arr = $.cookie(cookieType).split(',');
    }

    if (arr.length == 1) {
        $.removeCookie(cookieType);
    }
    else {
        arr = jQuery.grep(arr, function (value) {
            return value != ID;
        });
        $.cookie(cookieType, arr);
    }
}

// load compare box item
function loadCompareBoxItem() {
    $('.compare-box-container').show();
    var arr= [];
    if ($.cookie('phone') != null) {
        arr = $.merge(arr, $.cookie('phone').split(','));
    }
    if ($.cookie('pad') != null) {
        arr = $.merge(arr, $.cookie('pad').split(','));
    }
    if ($.cookie('wear') != null) {
        arr = $.merge(arr, $.cookie('wear').split(','));
    }
    arr = arr.toString();
    if (arr.length > 0) {
        $.get("Handler/HandlerCompare.ashx",
        { status: 'loadCompareBoxItem', products: arr },
        function (data) {

            var phoneCount = 0;
            var padCount = 0;
            var wearCount = 0;

            for (var i = 0; i < data.length; i++) {
                var Image = 'images/defaultPhone.png';
                var Name = data[i].Name.substr(0, 30);
                var ID = data[i].ID;
                var CategoryID = data[i].CategoryID;
                if (data[i].Image != null) {
                    Image = "data:image/jpg;base64," + data[i].Image;
                }

                var CompareType;
                switch (CategoryID) {
                    case 1:
                        CompareType = ".compare-item-phone";
                        phoneCount += 1;
                        break;
                    case 2:
                        CompareType = ".compare-item-pad";
                        padCount += 1;
                        break;
                    case 3:
                        CompareType = ".compare-item-wear";
                        wearCount += 1;
                        break;
                };
                var item = '<div class="compare-box-item">' +
                                                   '<div class="compare-img-container">' +
                                                   '<img class="box-item-img" src="' + Image + '" />' +
                                                   '</div>' +
                                                   '<p>' + Name + '</p>' +
                                                   '<div class="compare-box-cancel">' +
                                                   '<div class="' + ID + '">' +
                                                   '<img class="' + CategoryID + '" src="images/icon-cancel-130.png" />' +
                                                   '</div>' +
                                                   '</div>' +
                                                   '</div>';
                $(CompareType).append(item);
            }
            if (phoneCount >= wearCount && phoneCount >= padCount) {
                showCpBoxPhone();
            }
            else if (padCount >= phoneCount && padCount >= wearCount) {
                showCpBoxPad();
            }
            else {
                showCpBoxWear();
            }
            $(".compare-box-item").fadeTo(500, 1);
        });
    }
    
}

// 註冊item mouseenter mouseleave事件
$('#main-container')
.on('mouseenter', '.item-image-cmd-wrapper', itemMouseEnter)
.on('mouseleave', '.item-image-cmd-wrapper', itemMouseLeave);





$('.menu-cate').click(cateChoose);
$('.menu-brand').click(brandChoose);

function cateChoose() {
    if ($(this).attr('class').split(' ')[2] == 'menu-choose') {
        $('.menu-cate').removeClass('menu-choose');
        $('#mpItemPage').val(1);
        $.cookie('u_cate', 0);
        $.cookie('u_find', 0);
        $.cookie('ctr', 21);
        $(".main-item").remove();
        getItems();
    }
    else {
        var cateID = $(this).children('div').attr('class');
        $('#mpItemPage').val(1);
        $.cookie('u_cate', cateID);
        $.cookie('u_find', 0);
        $.cookie('ctr', 21);
        $('.menu-cate').removeClass('menu-choose');
        $(this).addClass('menu-choose');
        $(".main-item").remove();
        getItems();
    }    
};

function brandChoose() {
    if ($(this).attr('class').split(' ')[2] == 'menu-choose') {
        $('.menu-brand').removeClass('menu-choose');
        $('#mpItemPage').val(1);
        $.cookie('u_brand', 0);
        $.cookie('u_find', 0);
        $.cookie('ctr', 21);
        $(".main-item").remove();
        getItems();
    }
    else {
        var brandID = $(this).children('div').attr('class');
        $('#mpItemPage').val(1);
        $.cookie('u_brand', brandID);
        $.cookie('u_find', 0);
        $.cookie('ctr', 21);
        $('.menu-brand').removeClass('menu-choose');
        $(this).addClass('menu-choose');
        $(".main-item").remove();
        getItems();
    }    
};

function getItems() {
    var uPage = parseInt($('#mpItemPage').val());
    var uCate = $.cookie('u_cate');
    var uBrand = $.cookie('u_brand');
    var uFind = $.cookie('u_find');
    var ctr = parseInt($.cookie('ctr'));
    $('#mpIsItemGet').val(0);
    $.get("Handler/HandlerMainPage.ashx",
   { uPage: uPage, uCate: uCate, uBrand: uBrand, uFind: uFind },
   function (data) {
       for (var i = 0; i < data.length; i++) {
           var id = data[i].uboxId;
           var title = data[i].uboxTitle;
           var proId = data[i].productId;
           var pic = "images/phone.png";
           if (data[i].uboxImg != null) {
               pic = "data:image/jpg;base64," + data[i].uboxImg;
           }
           var item = '<div class="main-item ctr" style="display:none"><input type="hidden" class="page-ctr" value="' + ctr + '" /><div class="item-wrapper"><div class="item-image-cmd-wrapper"><div class="compare-cmd-wrapper"><button type="button" class="btn btn-danger btn-compare login-use"><span class="' + proId + '">加入比拚</span>' +
               '</button></div><div class="like-cmd-wrapper"><button type="button" class="btn btn-default login-use loveicon"><span class="' + id + '"><i class="glyphicon glyphicon-heart "></i></span></button></div><div class="item-image-holder"><div class="item-image-wrapper">' +
               '<img id="Article' + id + '"class="item-image" src="' + pic + '" /></div></div></div></div><div class="item-article"><p class="item-title">' + title + '</p></div></div>'
           $('#main-container').append(item);
           ctr = ctr + 1;
       }
       showElement($('.main-item'));
       $('#mpItemPage').val(uPage + 1);
       $('#mpIsItemGet').val(1);
       $.cookie('ctr', ctr);
   });
}

// cookie初始化
$.cookie('u_cate', 0);
$.cookie('u_brand', 0);
$.cookie('u_find', 0);
$.cookie('ctr', 21);
$(getItems());
$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() > $(document).height() - 300) {
        if ($('#mpIsItemGet').val() == 1) {
            getItems();
        }
    }
});

// 儲存首頁點擊記錄
$('body').on('click', '.ctr', function () {
    var ctrId = $(this).children('.page-ctr').val();
    $.get('Handler/HandlerCtr.ashx', { ctrId: ctrId });
})

// 首頁點擊ctr signalR
$(function () {

    //建立與Server端的Hub的物件，注意Hub的開頭字母一定要為小寫
    var ctr = $.connection.mainPageCtrHub;

    $("body").on('click','.ctr',function () {
        //呼叫Server端的sendMessage方法，並傳送使用者姓名及訊息內容給Server
        var ctrId = $(this).children('input').val();
        ctr.server.flashElement(ctrId);
    });

});